package servlets;

import java.io.IOException;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import security.Encryption;

import entities.Connection;
import entities.DeviceNC;

import managers.DeviceManager;
import managers.ConnectionManager;

/**
 * Servlet implementation class PairDevicesServlet
 */
@WebServlet("/PairDevices")
public class PairDevicesServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	@EJB
	DeviceManager dm;
	@EJB
	ConnectionManager cm;
	
    public PairDevicesServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String uuid = request.getParameter("uuid");
		String targetIp = request.getParameter("targetIP");
		String pairKey = request.getParameter("pairKey");
	
		DeviceNC targetNC = dm.getDevice(targetIp, true);
		DeviceNC hostNC = dm.getDevice(uuid, false);
		
		String pk = dm.getDevicePairKey(targetNC.getUuid());
		String encPairKey = Encryption.digest(pairKey);
		
		if(pk.equals(encPairKey)){
			Connection host = new Connection();
			host.setHost(hostNC.getUuid());
			host.setTarget(targetNC.getUuid());
			
			Connection target = new Connection();
			target.setHost(targetNC.getUuid());
			target.setTarget(hostNC.getUuid());
			
			cm.Create(host);
			cm.Create(target);
		}
		
		request.setAttribute("uuid", uuid);
		request.getRequestDispatcher("ConnectionList").forward(request, response);
	}

}
